package cn.mpq.payment.controller;
import cn.mpq.payment.common.Result;
import cn.mpq.payment.model.User;
import cn.mpq.payment.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;

@Controller
public class StudentController {
    @Autowired
    private UserService userService;

    @RequestMapping("/login.html")
    public String Register(){
        return "login";
    }
    @RequestMapping("/")
    public String Register1(){
        return "login";
    }
    @RequestMapping("/login")
    public String login() {
        return "login";
    }
    @RequestMapping("/ccq.html")
    public String ccq() {
        return "ccq";
    }
    @RequestMapping("/saveUser")
    @ResponseBody
    public Result saveUser(String username, String password, String email) {
        User user = new User();
        user.setUsername(username);
        user.setPassword(password);
        user.setEmail(email);
        try {
            userService.insert(user);
            return new Result(0,"注册成功");
        } catch(Exception e) {
            e.printStackTrace();
            return new Result(500,"注册失败");
        }
    }
    @RequestMapping("/loginUser")
    @ResponseBody
    public Result loginUser(String username, String password, HttpSession session) {
        UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken(username,password);
        Subject subject = SecurityUtils.getSubject();
        try {
            subject.login(usernamePasswordToken);   //完成登录
            User user=(User) subject.getPrincipal();
            session.setAttribute("user", user);
            return new Result(0,"登陆成功",user);
        } catch(Exception e) {
            return new Result(500,"登陆失败","");
        }
    }
    @RequestMapping("/logOut")
    public String logOut(HttpSession session) {
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
//        session.removeAttribute("user");
        return "login";
    }
}
